package com.fingard.dsp.bank.directbank.ccb41;

import jcifs.smb.SmbFile;

import java.io.File;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ISendSmsCode;
import com.fingard.dsp.bank.reqrespobj.sendsmscode.ReqCheckSmsCode;
import com.fingard.dsp.bank.reqrespobj.sendsmscode.ReqSendSmsCode;
import com.fingard.dsp.bank.reqrespobj.sendsmscode.RetAtsCheckSmsCode;
import com.fingard.dsp.bank.reqrespobj.sendsmscode.RetAtsSendSmsCode;
import com.fingard.dsp.bank.reqrespobj.sendsmscode.detail.RetAtsCheckSmsCodeDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/7/9.
 */
public class CCB41SendSmsCode extends CCB41Base implements ISendSmsCode {
    @Override
    public RetAtsSendSmsCode sendSmsCode(ReqSendSmsCode p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsCheckSmsCode checkSmsCode(ReqCheckSmsCode p_req) throws Exception {
        RetAtsCheckSmsCode retAts = new RetAtsCheckSmsCode(p_req.reqHeader);
        RetAtsCheckSmsCodeDetail detail = new RetAtsCheckSmsCodeDetail();
        try {
            if (StringHelper.isNullOrEmpty(bankFront.serverDownload)) {
                throw new Exception("前置机的serverDownload属性不能为空");
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CCB41Header bankHeader = new CCB41Header();
            bankHeader.tranId = "0002";
            bankHeader.tranDate = Format.Date8Format.format(new Date());
            String fileName = String.format("%1$s%2$s_AuthInfo.txt", getBankConfig().getValueAsString("saveDir"), p_req.smsCodeDetail.payAccNo);
            String authInfoStr = FileHelper.readFileText(fileName, getCharset());
            if (StringHelper.isNullOrEmpty(authInfoStr)) {
                throw new Exception("签约文件不存在或者签约信息为空");
            }
            //项目编号|申请流水id|name|证件号码|手机号|账号|收方账号
            String[] authInfo = authInfoStr.split("\\|");

            String compId = getBankConfig().getValueAsString("compid");
            bankHeader.compId = compId;
            bankHeader.seqNo = authInfo[1];
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Body");
            xmlWriter.writeElementString("Sms", p_req.smsCodeDetail.smsCode, true);//短信校验码
            xmlWriter.writeElementString("Reserve1", "", true);//保留1
            xmlWriter.writeElementString("Reserve2", "", true);//保留2
            xmlWriter.writeElementString("Reserve3", "", true);//保留3
            xmlWriter.writeElementString("Reserve4", "", true);//保留4
            xmlWriter.writeElementString("Reserve5", "", true);//保留5
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    detail.respCode = "0";
                    String retCode = tmpBkReader.getFirstText("/Root/Head/Retcode");
                    String retMsg = tmpBkReader.getFirstText("/Root/Head/Retmsg");
                    String signState = tmpBkReader.getFirstText("/Root/Body/Signstat");
                    String signid = tmpBkReader.getFirstText("/Root/Body/Signid");
                    if ("0000".equals(retCode)) {
                        if ("06".equals(signState)) {
                            detail.retCode = "3";
                        } else if ("08".equals(signState)) {
                            detail.retCode = "4";
                        } else {
                            detail.retCode = "5";
                        }
                        detail.outTransID = authInfo[1];
                    } else {
                        detail.retCode = "3";
                    }
                    detail.retMsg = retMsg;
                    //为签约信息查询做数据落地
                    if("4".equals(detail.retCode)||"5".equals(detail.retCode)) {
                        String[] filenames = getBankConfig().getValueAsString("ownAct").split(",");
                        if(filenames==null){
                            throw new Exception("标签ownAct配置有误：请核查！");
                        }
                        synchronized (CCB41Base.class) {
                            for (String ownFilename : filenames) {
                                //签约文件
                                String fullName = getBankConfig().getValueAsString("saveDir") + p_req.smsCodeDetail.payAccNo + File.separator + ownFilename + ".txt";
                                if (FileHelper.existFile(fullName)) {
                                    String[] signInfo = FileHelper.readFileText(fullName, getCharset()).split("\\|");
                                    if (signInfo.length == 10 && "2".equals(signInfo[9])) {
                                        //批量编号|申请流水id|name|证件号码|手机号|账号|收方账号|项目编号|签约会员号|签约情况（1-签约成功，2-签约失败，3-处理中）
                                        String item = getBankConfig().getMapValueByKey("PROTOCOL", ownFilename);
                                        String signtext = authInfoStr + "|" + item + "|" + signid + "|" + 3;
                                        FileHelper.writeFile(fullName, signtext, getCharset());
                                    }
                                } else {
                                    //批量编号|申请流水id|name|证件号码|手机号|账号|收方账号|项目编号|签约会员号|签约情况（1-签约成功，2-签约失败，3-处理中）
                                    String item = getBankConfig().getMapValueByKey("PROTOCOL", ownFilename);
                                    String signtext = authInfoStr + "|" + item + "|" + signid + "|" + 3;
                                    FileHelper.writeFile(fullName, signtext, getCharset());
                                }
                            }
                        }
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpStrRet[1];
            }
            if("4".equals(detail.retCode)||"5".equals(detail.retCode)) {
                if (bankFront.serverDownload.startsWith("smb:")) {
                    SmbFile[] smbFileList = SmbFileUtil.getSmbFiles(bankFront.serverDownload);
                    for (SmbFile smbFile : smbFileList) {
                        String[] result = sendEleFileToBank(smbFile);
                        if ("0000".equals(result[0])) {
                            WriteBankLogLn("上传文件:" + smbFile.getName() + " 返回结果：" + result[1]);
                        } else {
                            throw new Exception("文件上传失败：" + smbFile.getName() + "---  " + result[1]);
                        }
                    }
                } else {
                    String path = StringHelper.trimEnd(bankFront.serverDownload, "/");
                    path = StringHelper.trimEnd(path, "\\");
                    path = path + File.separator + p_req.smsCodeDetail.payAccNo;
                    File dir = new File(path);
                    if (dir == null) {
                        throw new Exception("前置机的serverDownload属性配置格式不规范");
                    }
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File[] listFiles = dir.listFiles();
                    if (listFiles == null || listFiles.length == 0) {
                        throw new Exception("上传目录不含任何文件，请核查");
                    }
                    String filename = "";
                    for (File file : listFiles) {
                        if (StringHelper.isNullOrEmpty(filename)) {
                            filename = file.getName();
                            continue;
                        }
                        if (filename.compareTo(file.getName()) < 0) {
                            filename = file.getName();
                        }
                    }
                    String[] result = sendEleFileToBank(path + File.separator + filename);
                    if ("0000".equals(result[0])) {
                        WriteBankLogLn("文件上传成功："+result[1]);
                    }else {
                        throw new Exception("文件上传失败:"+result[1]);
                    }
                }
            }
        } catch (Exception e) {
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }
}
